//
//  WBBaseViewController.swift
//  weibo
//
//  Created by wenquan wang on 11/18/16.
//  Copyright © 2016 wenquan wang. All rights reserved.
//

import UIKit

//class WBBaseViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
class WBBaseViewController: UIViewController {
    
    //var userLogon = true
    
    ///visitorView info dict
    var visitorInfo: [String: String]?
    
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    
    lazy var navItem = UINavigationItem()
    
    //not login nil.
    var tableView: UITableView?
    var refreshControl: CZRefreshControl?
    var isPullup = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        WBNetworkManager.shared.userLogin ? loadData() : ()
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(loginSuccess),
            name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotication),
            object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    override var title: String?{
        didSet {
            navItem.title = title
        }
    }
    
    func loadData(){
        refreshControl?.endRefreshing()
    }
}

// MARK: - set ui
extension WBBaseViewController{
    func setupUI(){
        view.backgroundColor = UIColor.white
        
        automaticallyAdjustsScrollViewInsets = false;

        self.setupNavigationBar()
        WBNetworkManager.shared.userLogin ? self.setupTableView() : setupVisitorView()
        
        
    }
    
    private func setupNavigationBar(){
        view.addSubview(navigationBar)
        
        navigationBar.items = [navItem]
        navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        //navigationBar.tintColor = UIColor.red
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray]
        navigationBar.tintColor = UIColor.orange
    }
    private func setupVisitorView(){
        let visitorView = WBVisitorView(frame: view.bounds)
        
        view.insertSubview(visitorView, belowSubview: navigationBar)
        
        print("visitorView\(visitorView)")
        
        visitorView.visitorInfo = visitorInfo
        
        //add event
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        //set tabbar button for annoy customer
        navItem.leftBarButtonItem = UIBarButtonItem(title: "Register", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "Login", style: .plain, target: self, action: #selector(login))
        
        
    }
    func setupTableView(){
        tableView = UITableView(frame: view.bounds, style: .plain)
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        //setup datasource and delegate
        tableView?.dataSource = self
        tableView?.delegate = self
        
        tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        //set refreshControl
        refreshControl = CZRefreshControl()
        
        tableView?.addSubview(refreshControl!)
        
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
    }
}

extension WBBaseViewController: UITableViewDataSource, UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0{
            return
        }
        let count = tableView.numberOfRows(inSection: section)
        
        if row == (count - 1) && !isPullup{
            print("up refresh!!")
            isPullup = true
            
            loadData()
        }
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 10
    }
}

//event for VisitorView
extension WBBaseViewController {
    
    @objc func loginSuccess(n: Notification) {
        print("login success \(n)")
        
        view = nil
        
        NotificationCenter.default.removeObserver(self)
        
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
    }
    
    @objc func register(){
        print("user register!")
    }
    
    @objc func login(){
        print("user login!")
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
}
